const {pageBase, getBase, saveBase, delBase} = require("../service/base.service");
const Record = require("../model/record.model");
const {pgParam} = require("../tool/toolPage");
const {whereBase, whereNoNull} = require("../tool/tool");
const {Op} = require("sequelize");
const {resSuccess, resBool, throwError} = require("../tool/toolBase");
const {errDoMsg} = require("../constant/comConstant");

//接口回调函数
class RecordController {
    async saveData(ctx, next) {
        //1. 获取数据
        const data = ctx.request.body
        try {
            //2. 操作数据库
            const res = await saveBase(Record, data, "id");
            //3. 返回结果
            ctx.body = resSuccess(res);
        } catch (err) {
            throw throwError(err, errDoMsg.SAVEUPD);
        }
    }

    async pageRecord(ctx, next) {
        //1. 获取数据
        const data = ctx.request.body
        try {
            //2. 操作数据库

            let where = whereBase(data, {}, ["person"]);
            whereNoNull(data, where, "title", {[Op.substring]: data.title});
            whereNoNull(data, where, "context", {[Op.substring]: data.context});
            // console.log(where)
            const res = await pageBase(Record, pgParam(data), where);
            //3. 返回结果
            ctx.body = resSuccess(res);
        } catch (err) {
            throw throwError(err, errDoMsg.PAGE);
        }
    }

    async getRecord(ctx, next) {
        //1. 获取数据
        const data = ctx.request.body
        try {
            //2. 操作数据库
            let where = {id: data.id};
            const res = await getBase(Record, where);
            //3. 返回结果
            ctx.body = resSuccess(res);
        } catch (err) {
            throw throwError(err, errDoMsg.SELECT);
        }
    }

    async delRecord(ctx, next) {
        const data = ctx.request.body
        try {
            let where = {id: data.id}
            const res = await delBase(Record, where);
            ctx.body = resBool(res);
        } catch (err) {
            throw throwError(err, errDoMsg.DEL);
        }
    }
}

module.exports = new RecordController()